package com.aoeai.rg

import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Scaffold
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import com.aoeai.rg.common.ui.components.RgTabRow
import com.aoeai.rg.language.data.repository.LanguageRepository
import com.aoeai.rg.language.manager.LanguageManager
import com.aoeai.rg.language.manager.LanguageManager.LocalLanguageContext
import com.aoeai.rg.language.manager.LanguageManager.createLanguageContext
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            init()
            App()
        }
    }

    private fun init() {
        val repository = LanguageRepository(this)
        val applicationScope = CoroutineScope(SupervisorJob() + Dispatchers.Main)
        LanguageManager.init(repository, applicationScope)
    }
}

@Composable
fun App() {
    // 获取当前选择的语言代码
    val languageCode by LanguageManager.currentLanguageCode.collectAsState()
    val context = LocalContext.current

    // 创建应用了特定语言的Context
    val languageContext = remember(languageCode) {
        if (languageCode.isEmpty()) context else context.createLanguageContext(languageCode)
    }

    // 提供语言Context给整个应用
    CompositionLocalProvider(LocalLanguageContext provides languageContext) {
        var currentScreen: Destination by remember { mutableStateOf(Home) }

        Scaffold(
            contentWindowInsets = WindowInsets(0, 0, 0, 0),
            bottomBar = {
                RgTabRow(
                    allScreens = rallyTabRowScreens,
                    onTabSelected = { screen -> currentScreen = screen },
                    currentScreen = currentScreen
                )
            }
        ) { innerPadding ->
            Box(Modifier.padding(innerPadding)) {
                currentScreen.screen()
            }
        }
    }
}